/**
 * Created by lenovo on 2016/10/20.
 */
(function () {
    $.ajax({
        url: wxUrl,
        data: {'url': window.location.href},
        type: "get",
        success: function (data) {
            if (data.errcode == "0") {
                var noncestr = data.noncestr;
                var timestamp = data.timestamp;
                var signature = data.signature;
                scanCode(noncestr, timestamp, signature);
            } else {
                // alert(data.errmsg);
            }
        }
    });
    var scanCode = function (str, timestamp, signature) {

            wx.config({
                beta: true,
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId:appId, // 必填，企业号的唯一标识，此处填写企业号corpid
                timestamp: timestamp, // 必填，生成签名的时间戳
                nonceStr: str, // 必填，生成签名的随机串
                signature: signature,// 必填，签名，见附录1
                jsApiList: [
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage',
                    'onMenuShareQQ',
                    'onMenuShareWeibo',
                    'onMenuShareQZone',
                    'startRecord',
                    'stopRecord',
                    'onVoiceRecordEnd',
                    'playVoice',
                    'pauseVoice',
                    'stopVoice',
                    'onVoicePlayEnd',
                    'uploadVoice',
                    'downloadVoice',
                    'chooseImage',
                    'previewImage',
                    'uploadImage',
                    'downloadImage',
                    'translateVoice',
                    'getNetworkType',
                    'openLocation',
                    'getLocation',
                    'hideOptionMenu',
                    'showOptionMenu',
                    'hideMenuItems',
                    'showMenuItems',
                    'hideAllNonBaseMenuItem',
                    'showAllNonBaseMenuItem',
                    'closeWindow',
                    'scanQRCode',
                    'chooseWXPay',
                    'openProductSpecificView',
                    'addCard',
                    'chooseCard',
                    'openCard',
                    'chooseVideo',
                    'uploadVideo',
                    'onVideoUploadProgress'
                ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });

        wx.ready(function () {
            wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                    //console.log(res);
                    var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    var speed = res.speed; // 速度，以米/每秒计
                    var accuracy = res.accuracy; // 位置精度
                    $("#latitude").val(latitude);
                    $("#longitude").val(longitude);
                    $.ajax({
                        url: 'http://api.map.baidu.com/geocoder/v2/?ak=BoDHWfB34TUhSDodZSudcbo0&callback=renderReverse&location=' + latitude + ',' + longitude + '&output=json&pois=1',
                        type: "get",
                        dataType: "jsonp",
                        jsonp: "callback",
                        success: function (data) {
                            //console.log(data);
                            var name = (data.result.formatted_address);
                            $("#detailarea").val(name);

                            if (typeof callback == "function") {
                                callback(data);
                            }

                        }
                    });
                },cancel:function(res){
                    var url=uploadUrl+"weixin/bm/index";
                    window.location.href=url;
                }
            });
        });
        }





})()

var serverId = new Map();
var vidoId=new Map();
var viewId=new Map();
var shipId;
var localimgId = new Array();
var localIds = new Array();
var num = 0;
/**
 * 选取图片(拍照或从手机相册中选图接口)
 */
function chooseImg() {
    if(num>=3){
        alert("最多上传3张图片！");
        return ;
    }
    var count=3-parseInt(num);
    wx.chooseImage({
        count: count, // 默认9
        sizeType: [ 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            num+=res.localIds.length;
            if(num>3){
                alert("最多上传3张图片！");
                return ;
            }
            localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          /*  localimgId = localimgId.concat(localIds);*/
            showImage();
            localImg();
        }
    });
}
/**
 * 上传图片
 */
function localImg() {
    var localid = localIds.pop();
    wx.uploadImage({
        localId: localid,
        isShowProgressTips: 2, // 默认为1，显示进度提示
        success: function (res) {
            uploadImg(res.serverId,localid,2);
        },
        fail: function (res) {
             alert(JSON.stringify(res));
        }
    });
}
/**
 * 展示图片
 */
function showImage() {
    $.each(localIds, function (i, n) {
        $('#img').append("<li class='weui_uploader_file' ><img src='" + n + "' onclick='showAutoImg(\"" + n + "\")' width='79px' height='79px'/><div class='sxsb_close' onclick='revokeImg(this,\""+n+"\");'></div></li>");
       });
}
/**
 * 上传到后台
 * @param serviceId
 * @param localid
 * @param mark
 */
function uploadImg(serviceId,localid,mark){//mark:  0-图片  1:视屏 2：语音
    var url=uploadUrl+"api/callPolice/uploadimg/"+serviceId+"/"+mark;
        $.ajax({
        url: url ,
        type: "get",
        dataType: "json",
        success: function (resp) {
            if (resp && resp.succ) {
                serverId.put(localid,resp.data);
                if (localIds.length > 0) {
                    localImg();
                }
            }
        }
    });
}
/**
 * 图片预览
 * @param obj
 */
function showAutoImg(obj) {
    $.showPic(obj);
}
/**
 * 删除图片
 * @param obj
 * @param n
 */
function revokeImg(obj,n) {
    num-=1;
    $(obj).parent("li").remove();
    var imgkey =  n;
    serverId.keys=prototyperemove(serverId.keys,imgkey);
    serverId.data=prototyperemove(serverId.data,imgkey);
}
/**
 * 录音
 */
var luyId="";
function luy() {
    luyId="";
    vidoId=new Map();
    var a=60;
    document.getElementById("time").innerHTML =a;
    wx.startRecord();
    send();
}
/**
 * 手动停止录音
 */
function queR(){
    stopLuy();
}
/**
 * 停止录音
 */
function stopLuy() {
    wx.stopRecord({
        success: function (res) {
            luyId = res.localId;
            $(".wxbj_lysc1").css("display","none");
            $(".wxbj_lysc").css("display","block");
        }
    });
}
/**
 * 确认上传录音
 */
function queR2(){
   /* $("#zhezhao").remove();
    var oMask=document.getElementById("zhezhao");
    if(oMask!=null)
    {
        document.body.removeChild(oMask);
    }*/
    $("#zhezhao").css("display","none");
    $("#lysc_pup3").css("display","none");
    $(".wxbj_lysc1").css("display","block");
    uplodVido();}
/**
 * 录音上传到后台
 * @param serviceId
 * @param luyId
 * @param mark
 */
function vido(serviceId,luyId,mark){
    var url=uploadUrl+"api/callPolice/uploadimg/"+serviceId+"/"+mark;
    $.ajax({
        url: url ,
        type: "get",
        dataType: "json",
        success: function (resp) {
            if (resp && resp.succ) {
                vidoId.put(luyId,resp.data);
                $("#lysc_pup3").css("display","none");
                $(".wxbj_lysc").css("display","block");
            }
        }
    });
}
function stopV(){
    wx.stopVoice({
        localId: luyId // 需要停止的音频的本地ID，由stopRecord接口获得
    });
    clearTimeout(dtime);
}
/**
 * 删除录音
 */
function deleteVio(){
    luyId="";
    vidoId=new Map();
    /*$("#zhezhao").remove();
    var oMask=document.getElementById("zhezhao");
    if(oMask!=null){
        document.body.removeChild(oMask);
    }*/
    $("#zhezhao").css("display","none");
    $("#lysc_pup5").css("display","none");
    $(".wxbj_lysc1").css("display","none");
    $(".wxbj_lysc").css("display","block");
}
function deleteVio2()
{
    luyId="";
    vidoId=new Map();
  /*  $("#zhezhao").remove();
    var oMask=document.getElementById("zhezhao");
    if(oMask!=null){
        document.body.removeChild(oMask);
    }*/
    $("#zhezhao").css("display","none");
    $("#lysc_pup5").css("display","none");
    $(".wxbj_lysc1").css("display","none");
    $(".wxbj_lysc").css("display","block");
}
/**
 * 播放录音
 *
 */
function playV() {
    if($("#btn_rt4").text()=="停止"){
        stopV();
    }else{
        wx.playVoice({
            localId: luyId // 需要播放的音频的本地ID，由stopRecord接口获得
        });
        wx.onVoicePlayEnd({
            success: function (res) {
                $("#lysc_pup5").css("display","none");
                /*$("#zhezhao").remove();
                var oMask=document.getElementById("zhezhao");
                if(oMask!=null){
                    document.body.removeChild(oMask);
                }*/
                $("#zhezhao").css("display","none");
            }
        });
    }

}
/**
 * 超过1分钟自动停止
 */
function send(){
    var i =$("#time").html();
    i--;
    if(i==-1)
        return null;
    document.getElementById("time").innerHTML = i;
    wx.onVoiceRecordEnd({
        // 录音时间超过一分钟没有停止的时候会执行 complete 回调
        complete: function (res) {
            luyId="";
            vidoId=new Map();
            luyId = res.localId;
            $(".wxbj_lysc1").css("display","none");
            $(".wxbj_lysc").css("display","block");
            uplodVido();
           clearTimeout(dtime);
        }
    });
    var dtime=setTimeout("send();",1000);

}
function uplodVido(){
    $("#lysc_pup3").css("display","none");
    wx.uploadVoice({
        localId: luyId, // 需要上传的音频的本地ID，由stopRecord接口获得
        isShowProgressTips: 2, // 默认为1，显示进度提示
        success: function (res) {
            var serverId = res.serverId; // 返回音频的服务器端ID
            vido(serverId,luyId,4)
        }
    });
}
/**
 * 选取视屏
 */
var ID="";
function view() {
    wx.invoke('chooseVideo', {
        "sourceType": 'album|camera',
        "maxDuration": "60",
        "camera": "back"
    }, function (res) {
        //这里是回调函数
        if(res.err_msg=="chooseVideo:ok"){
            ID = res.localId;
            upload();
        }
    });
}
function upload() {
    viewId=new Map();
    WeixinJSBridge.invoke('uploadVideo', {
        "appId": appId,
        "localId": ID,//"wxLocalResource://43152509943431"
    }, function (res) {
        shipId=res.serverId;
        uploadView(shipId,ID,3);

    });
   /* WeixinJSBridge.on('onVideoUploadProgress', function (res) {
        document.querySelector('#upload-progress').innerHTML = res.localId + ': ' + res.percent + '%';
    });*/
}
function uploadView(serviceId,luyId,mark){
    var url=uploadUrl+"api/callPolice/uploadimg/"+serviceId+"/"+mark;
    $.ajax({
        url: url ,
        type: "get",
        dataType: "json",
        success: function (resp) {
            if (resp && resp.succ) {
                viewId.put(luyId,resp.data);
                    $("#addView").html("视频已上传");
            }
        }
    });
}
